<script lang="ts" setup>
import type { UploadFile, UploadRawFile } from 'element-plus'
import * as XLSX from 'xlsx'
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
const props = defineProps<{
  address: string
  templateHref: string
  numUploadLabel: string
  isLinkbutton?: boolean
  icon?: boolean
  color?: string
}>()
const emits = defineEmits(['updateIdList'])
const jsonData = ref([])
const readExcelData = async (file: UploadFile) => {
  if (!file) return

  try {
    const data = await fileToBinaryString(file.raw as UploadRawFile)
    const workbook = XLSX.read(data, { type: 'binary' })
    const firstSheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[firstSheetName]
    jsonData.value = XLSX.utils.sheet_to_json(worksheet)
  } catch (error) {
    console.error('Error reading the file', error)
    // 处理错误或通知用户
    ElMessage.error(error!)
  }
}
watch(jsonData, (newValue) => {
  const joinedIds = newValue.map((item) => item['编号']).join('@')
  // 发出自定义事件给父组件
  emits('updateIdList', joinedIds)
})

const fileToBinaryString = (file: Blob): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e) => resolve(e.target?.result as string)
    reader.onerror = (e) => reject(e)
    reader.readAsBinaryString(file)
  })
}

const handlenumFileChange = (file: UploadFile) => {
  readExcelData(file)
}
</script>
<template>
  <el-upload
    ref="numUpload"
    :auto-upload="false"
    :on-change="handlenumFileChange"
    :action="props.address"
    :limit="1"
    :show-file-list="false"
    class="import-data-upload"
  >
    <template #trigger>
      <el-button :link="isLinkbutton" plain type="primary" :color="color" w-full>
        <el-icon v-if="icon"><Download /></el-icon>
        {{ props.numUploadLabel }}</el-button
      >
    </template>
    <template #tip>
      <div leading-17 mt-2 class="text-[#999999]">
        (请根据所下载的模板格式进行数据导入,<a
          class="text-[#1d93ff] cursor-pointer"
          :href="props.templateHref"
          download="导入模板"
          >下载模板</a
        >)
      </div>
    </template>
  </el-upload>
</template>

<style scoped lang="scss">
.import-data-upload {
  --at-apply: mt-10;
  > :deep(.el-upload) {
    --at-apply: w-7/10;
  }
}
</style>
